<template>
  <div class="treelist-container">
    <el-input
      v-if="filterable"
      placeholder="输入关键字"
      size="small"
      v-model="filterText"
      suffix-icon="el-icon-search"></el-input>
    <div :class="maxHeight?'treelist-panel':''" :style="{maxHeight:maxHeight?maxHeight+'px':'',overflow: 'auto'}">
      <el-tree
        ref="treelist"
        node-key="id"
        :show-checkbox="showCheckbox"
        :data="treeData"
        :default-checked-keys="mDefaultCheckedKeys"
        :default-expand-all="defaultExpandAll"
        :default-expanded-keys="unfoldNodes"
        :expand-on-click-node="expandOnClickNode"
        :highlight-current="highlightCurrent"
        :props="defaultProps"
        check-on-click-node
        :filter-node-method="filterNode"
        @node-click="handleNodeClick"
        @check-change="checkChange"
        @check="check"
        :empty-text="emptyText"></el-tree>
    </div>
  </div>
</template>
<script>
import { codeProvider } from "../../../assets/js/provider.js";
import Toolkit from '../../../assets/js/toolkit.js'
export default {
  name: "dx-treelist",
  props: {
    codeType: String,
    defaultExpandedKeys: Array,
    showCheckbox : {type:Boolean,default:false},
    expandLevel: { type: Number, default: 3 },
    defaultCheckedKeys : Array,
    expandOnClickNode : { type: Boolean, default: false },
    defaultExpandAll : { type: Boolean, default: false },
    highlightCurrent : { type: Boolean, default: true },
    condition: { type: Object, default: () => {} },
    maxHeight: { type: Number, default: 0},
    filterable: { type: Boolean, default: false }
  },
  computed : {
    mDefaultCheckedKeys : {
      get(){

        if(this.treeData && this.showCheckbox){
            let checkKeys = this.defaultCheckedKeys;
            // if(this.eq_array(this.checkKeys,checkKeys)) return this.checkKeys;

            let leafCheckKeys = this.getLeafCheckeds(this.treeData,this.defaultCheckedKeys);

            // console.log('leafCheckKeys',leafCheckKeys,this.defaultCheckedKeys);
            return leafCheckKeys;

        }
        return null;
      },
      set(val){

      }
    }
  },
  watch: {
    filterText(val) {
      this.$refs.treelist.filter(val);
    },
    codeType(val) {
      //代码模型变化
      if(_.eq(this.mCodeType,val)){
        return;
      }
      this.mCodeType = val;
      this.getTreeData();
    },
    condition(val) {
      //条件变化
      //代码模型变化
      if(this.eq_object(this.mCondition,val)){
        return;
      }

      this.mCondition = val;
      this.getTreeData();
    }
  },
  data() {
    return {
      emptyText:'数据加载中...',
      filterText : "",
      parentValue : 0,
      treeData: [],
      defaultProps: { children: "childrens", label: "name", key: "id" },
      treeSelectedId: "",
      unfoldNodes: [],
      mCondition : this.condition,
      mCodeType : this.codeType,
      checkKeys : [],
    };
  },
  mounted() {},
  created() {
    // console.log('condition->treelist',this.condition);
    this.unfoldNodes = this.defaultExpandedKeys;
    this.getTreeData();
  },
  methods: {
    filterNode(value, data) {
      if (
        data[this.defaultProps.label] &&
        data[this.defaultProps.label].indexOf(value) >= 0
      ){
        return true;
      }
      return false;
      // return data.id.indexOf(value) !== -1;
    },
    /**
     * 获取子节点
     */
    getChilds(codeList, parentField, parentValue) {
      return _.filter(codeList, item => {
        return item[parentField] == parentValue;
      });
    },
    /**
     * 创建树结构
     */
    buildTreeNode(codeList, textField, valueField, parentField, parentValue) {
      let nodes = [];
      let childrens = this.getChilds(codeList, parentField, parentValue);
      if (childrens && childrens.length > 0) {
        for (let i = 0; i < childrens.length; i++) {
          let childs = this.buildTreeNode(
            codeList,
            textField,
            valueField,
            parentField,
            childrens[i][valueField]
          );

          nodes.push({
            id  : childrens[i][valueField],
            name: childrens[i][textField],
            currentNode : childrens[i],
            childrens: childs
          });
        }
      }
      return nodes;
    },
    /**
     * 查询符合的节点
     */
    getTreeNodeById(val, tree, key) {

      if (!key) {
        key = this.defaultProps.key;
      }
      if (!tree) {
        tree = this.treeData;
      }
      let _temp = "";
      let findById = (oTree, val, key) => {
        for (let i = 0; i < oTree.length; i++) {
          let item = oTree[i];
          if (item[key] && item[key] == val) {
            _temp = item;
          } else {
            let childrens = item[this.defaultProps.children];
            if (childrens && childrens.length > 0) {
              findById(childrens, val, key);
            }
          }
        }
      };
      findById(tree, val, key);
      return _temp;
    },
    //去除父节点
    getLeafCheckeds(tree ,checkeds){
      if(!checkeds || !Array.isArray(checkeds)) return [];
      checkeds = checkeds.map(item=>String(item));
      let arr = [];
      let index = 0;
      let pushNode = (oTree, array) => {

        oTree.forEach(item => {

          let childrens = item[this.defaultProps.children];
          if (childrens.length > 0) {
            pushNode(childrens, array);
          }else{//子节点
            //且在备选数组中
            if(_.indexOf(checkeds,String(item[this.defaultProps.key])) >= 0){
               array.push(item[this.defaultProps.key]);
            }
          }
          index++;
        });
      };

      pushNode(tree, arr);
      return arr;
    },
    refresh(defaultExpandKeys,selectkey){
      this.getTreeData(defaultExpandKeys ,selectkey);
    },
    /**
     *展开
     */
    getUnfoldNodes(tree, level) {
      let arr = [];
      let index = 0;
      let pushNode = (oTree, array) => {

        oTree.forEach(item => {

          let childrens = item[this.defaultProps.children];
          if (childrens.length > 0 && index < level) {
            array.push(item[this.defaultProps.key]);
            pushNode(childrens, array);
          }
          index++;
        });
      };

      pushNode(tree, arr);
      return arr;
    },
    /**
     * 获取显示数据
     */
    getTreeData(defaultExpandKeys,selectkey) {
      codeProvider.getList(this.codeType,this.condition||{}).then(resp => {
        let textField = resp.textField;
        let valueField = resp.valueField;
        let parentValue = resp.parentValue;
        let parentField = resp.parentField;

        let codeList = resp.codeList;
        if (codeList && codeList.length > 0) {

          this.parentValue = parentValue;
          this.treeData = this.buildTreeNode(
            codeList,
            textField,
            valueField,
            parentField,
            parentValue
          );


          this.unfoldNodes = this.getUnfoldNodes(
            this.treeData,
            this.expandLevel
          );
          //默认展开
          if(defaultExpandKeys && Array.isArray(defaultExpandKeys)){
            this.unfoldNodes = this.unfoldNodes || [];
            this.unfoldNodes = _.uniq(this.unfoldNodes.concat(defaultExpandKeys));
          }
          //默认选中
          if(this.showCheckbox){
            this.mDefaultCheckedKeys = selectkey;
          }else{
            if(selectkey){
              this.$nextTick(()=>{
                this.setCurrentKey(selectkey);
              });
            }
          }
          
          // console.log('expandLevel->',this.expandLevel);
          // console.log('unfoldNodes',this.unfoldNodes);
          this.$emit("tree-loaded", this.treeData);
        }else{

          this.emptyText = '无数据';
        }
      });
    },
    setCurrentKey(id) {
      this.$refs.treelist.setCurrentKey(id);
    },
    /**
     * 节点选择
     */
    handleNodeClick(node) {
      if (node.id) {
        this.treeSelectedId = node.id;
        this.$emit("node-click", node);
      }
    },
    checkChange(){
      this.$emit("check-change" , ...arguments);
    },
    check(node,checks){
      this.checkKeys = checks.checkedKeys.concat(checks.halfCheckedKeys);
      this.$emit("check" , ...arguments);
    }
  },
  mixins:[Toolkit]
};
</script>
<style scoped>
/* 菜单滚动条 */

.treelist-panel::-webkit-scrollbar {
  z-index: 11;
  width: 6px;
}
.treelist-panel::-webkit-scrollbar-track,
.treelist-panel::-webkit-scrollbar-corner {
  background: #fff;
}
.treelist-panel::-webkit-scrollbar-thumb {
  border-radius: 5px;
  width: 6px;
  background: #b4bccc;
}
.treelist-panel::-webkit-scrollbar-track-piece {
  background: #fff;
  width: 6px;
}
</style>


